package net.hancl.modules.sys.controller.converter;

import net.hancl.common.annotation.PermissionAnnot;
import net.hancl.common.constants.MenuReadWrite;
import net.hancl.modules.sys.service.ILogService;
import net.hancl.modules.sys.utils.UserUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.MethodParameter;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

import java.lang.annotation.Annotation;
import java.util.Set;

public class PermissionAnnotResolver implements HandlerMethodArgumentResolver {
    static Logger logger = LoggerFactory
            .getLogger(PermissionAnnotResolver.class);

    @Autowired
    private ILogService logService;

    @Autowired
    public UserUtils userUtils;

    public boolean supportsParameter(MethodParameter parameter) {

        Annotation[] as = parameter.getMethodAnnotations();
        if (as == null) {
            return false;

        }

//		SetData.whiteList.contains(request.getRequestURI())

        for (Annotation a : as) {
            if (a.annotationType() == PermissionAnnot.class) {
                PermissionAnnot permissionAnnot = (PermissionAnnot) a;
                //如果这个权限标记为只写，就不会做为一个权限拦截了
                if(permissionAnnot.readWrite().getValue()==MenuReadWrite.Write.getValue()){
                    return false;
                }

                Set<String> set = userUtils.getUserPermisson();
                if (set.contains(permissionAnnot.id())) {
                    return false;
                }
                logger.error("permissionAnnotResolver >>> resolveArgument throw new org.apache.shiro.authz.AuthorizationException(\"没有访问权限\")==id:{}",permissionAnnot.id());
                return true;
            }
        }

        return false;
    }

    public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer, NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception {
        throw new org.apache.shiro.authz.AuthorizationException("没有访问权限");
    }
}
